/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package qlvbdq.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import qlvbdq.dconnection.SQLServerConnect;
import qlvbdq.dto.KhachHangDTO;

/**
 *
 * @author tuan
 */
public class KhachHangDAO {
    private static final String MaKhachHang = "MaKH000";
    private static final int lengthMa = 8;
    
    public KhachHangDAO() {
    }
    
    public String getNewMaKhachHang() throws SQLException {
        String MaKH = "";
        int maxMa = 0;
        ResultSet rs = SQLServerConnect.getInstance().getDataFromStore("GetAllKhachHangFromDataBase", null);
        while (rs.next()) {
            int temp = Integer.parseInt( rs.getString("MAKHACHHANG").substring(lengthMa) );
            if (maxMa < temp) {
                maxMa = temp;
            }
        }
        maxMa ++;
        MaKH = MaKH.concat(MaKhachHang + maxMa);
        return MaKH;
    }
    
    public KhachHangDTO getKhachHangByMaKH(String MaKH) throws SQLException {
        Object[] objs = { MaKH };
        ResultSet rs = SQLServerConnect.getInstance().getDataFromStore("GetKhachHangByMaKHFromDataBase(?)", objs);
        KhachHangDTO khachHang = new KhachHangDTO();
        while (rs.next()){
            khachHang.setMaKhachHang(rs.getString("MAHANGGC"));
            khachHang.setTenKhachHang(rs.getString("TENKHACHHANG"));
            khachHang.setDiaChi(rs.getString("DIACHI"));
            khachHang.setEmail(rs.getString("EMAIL"));
            khachHang.setSdt(rs.getString("SDT"));
            khachHang.setCmnd(rs.getString("CMND"));
            khachHang.setLaKhachQuen(Boolean.parseBoolean(rs.getString("LAKHACHQUEN")));
            khachHang.setSoTienNo(rs.getLong("SOTIENNO"));
        }
        
        return khachHang;
    }
    public int updateKhachHang(KhachHangDTO khachHang) {
        Object[] objs = { khachHang.getMaKhachHang(), khachHang.getTenKhachHang(), khachHang.getDiaChi(), khachHang.getSdt(),
                khachHang.getCmnd(), khachHang.getEmail(), khachHang.getLaKhachQuen(), khachHang.getSoTienNo()};
        return SQLServerConnect.getInstance().updateDataToDatabase("UpdateKhachHangToDataBase(?, ?, ?, ?, ?, ?, ?, ?)", objs);
    }
    
    public int deleteKhachHangByMa(String MaKH) {
        Object[] objs = { MaKH };
        return SQLServerConnect.getInstance().updateDataToDatabase("DeleteKhachHangFromDataBase(?)", objs);
    }
    
    public int insertKhachHang(KhachHangDTO khachHang) {
        Object[] objs = { khachHang.getMaKhachHang(), khachHang.getTenKhachHang(), khachHang.getDiaChi(), khachHang.getSdt(),
                khachHang.getCmnd(), khachHang.getEmail(), khachHang.getLaKhachQuen(), khachHang.getSoTienNo()};
        return SQLServerConnect.getInstance().updateDataToDatabase("InsertKhachHangToDataBase(?, ?, ?, ?, ?, ?, ?, ?)", objs);
    }
}
